package user

import (
	"context"
	"fmt"

	"golang.org/x/crypto/bcrypt"
)

type Service interface {
	// 创建用户
	CreateUser(context.Context, *CreateUserRequest) (*User, error)
	// 查询用户（校验密码）
	DescribeUser(context.Context, *DescribeUserRequest) (*User, error)
	// 删除用户
	DeleteUser(context.Context, *DeleteUserRequest) error
}

type CreateUserRequest struct {
	Username string            `json:"username"`
	Password string            `json:"password"`
	Role     Role              `json:"role"`
	Label    map[string]string `json:"label" gorm:"serializer:json"`
	// 判断密码是否加密
	isHashed bool
}

func NewCreateUserRequest() *CreateUserRequest {
	return &CreateUserRequest{
		Label: make(map[string]string),
	}
}

// 用户校验的方法
func (c *CreateUserRequest) Validate() error {
	if c.Username == "" || c.Password == "" {
		return fmt.Errorf("用户名或密码为空")
	}
	return nil
}

// 给用户密码加密，避免明文保存
func (req *CreateUserRequest) PasswordHash() {
	if req.isHashed {
		return
	}

	b, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	req.Password = string(b)
	req.isHashed = true
}

// 通过name、id查询
type DescribeUserRequest struct {
	DescribeBy    DescribeBy `json:"describe_by"`
	DescribeValue string     `json:"describe_value"`
}

func NewDescribeUserRequest_By_Username(username string) *DescribeUserRequest {
	return &DescribeUserRequest{
		DescribeBy:    DESCRIBEBY_USERNAME,
		DescribeValue: username,
	}
}

func NewDescribeUserRequest_By_ID(id string) *DescribeUserRequest {
	return &DescribeUserRequest{
		DescribeBy:    DESCRIBEBY_ID,
		DescribeValue: id,
	}
}

type DeleteUserRequest struct {
	ID string
}

func NewDeleteUserRequest() *DeleteUserRequest {
	return &DeleteUserRequest{}
}
